package com.jinduplan.planmanager.ui.fragment

import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.view.*
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.baidu.location.BDAbstractLocationListener
import com.baidu.location.BDLocation
import com.baidu.location.Poi
import com.baidu.mapapi.map.*
import com.baidu.mapapi.model.LatLng
import com.cxz.kotlin.baselibs.adapter.CustomRecyclerAdapter
import com.cxz.kotlin.baselibs.adapter.ViewHolder
import com.cxz.kotlin.baselibs.base.BaseMvpActivity
import com.cxz.kotlin.baselibs.base.BaseMvpFragment
import com.cxz.kotlin.baselibs.base.changeDrawalbeColor
import com.cxz.kotlin.baselibs.config.AppConfig
import com.cxz.kotlin.baselibs.interfaces.OnCountDownCallBack
import com.cxz.kotlin.baselibs.rx.bus.BusEvent
import com.cxz.kotlin.baselibs.rx.bus.RxBus
import com.cxz.kotlin.baselibs.utils.GsonHelper
import com.cxz.kotlin.baselibs.utils.LogUtil
import com.cxz.kotlin.baselibs.utils.Preference
import com.cxz.kotlin.baselibs.utils.UserInfoUtil
import com.fphoenixcorneae.util.toast.ToastUtil
import com.huantansheng.easyphotos.callback.SelectCallback
import com.huantansheng.easyphotos.models.album.entity.Photo
import com.jinduplan.planmanager.BuildConfig
import com.jinduplan.planmanager.R
import com.jinduplan.planmanager.app.App
import com.jinduplan.planmanager.bean.WeatherBean
import com.jinduplan.planmanager.bean.WeatherForecastBean
import com.jinduplan.planmanager.constant.Constant
import com.jinduplan.planmanager.mvp.contract.MainFragmentContract
import com.jinduplan.planmanager.mvp.presenter.MainFragmentPresenter
import com.jinduplan.planmanager.service.LocationService
import com.jinduplan.planmanager.ui.activity.MainActivity
import com.jinduplan.planmanager.ui.activity.clockin.ClockInActivity
import com.jinduplan.planmanager.ui.activity.clockin.ClockInComfirActivity
import com.jinduplan.planmanager.ui.activity.msg.MessageActivity
import com.jinduplan.planmanager.ui.activity.project.ProjectUploadActivity
import com.jinduplan.planmanager.utils.DateUtils
import com.jinduplan.planmanager.utils.DialogUtil
import com.jinduplan.planmanager.utils.FormatterEnum
import com.jinduplan.planmanager.utils.ResUtil
import com.jinduplan.planmanager.widgets.MapClickInDialog
import com.jinduplan.planmanager.widgets.SafeTipsDialog
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.disposables.Disposable
import kotlinx.android.synthetic.main.fragment_main.*
import kotlinx.android.synthetic.main.fragment_main.bmapView
import kotlinx.android.synthetic.main.fragment_main.tv_location
import kotlinx.android.synthetic.main.fragment_mine.*
import java.lang.ref.WeakReference
import java.util.ArrayList

class MainFragment : BaseMvpFragment<MainFragmentContract.View, MainFragmentContract.Presenter>(),
    MainFragmentContract.View {

    private val locationService: LocationService by lazy {
        (AppConfig.getApplication() as App).locationService
    }
    var mProjectId: String by Preference(Constant.PROJECTID, "")
    var mProjiectName: String by Preference(Constant.PROJECT_NAME, "")
    var project_addr: String by Preference(Constant.PROJECT_ADDR, "")

    // 是否首次定位
    public var isFirstLoc = true

    var mLatitude = 0.toDouble()
    var mLongitude = 0.toDouble()
    var mPoiName = ""
    var mAddr = ""
    var mprovince = ""
    var mCity = ""
    var mArea = ""
    var mlocData: MyLocationData? = null
    var mBitmap: Bitmap? = null
    private var mDisposable: Disposable? = null
    private var mDisposable2: Disposable? = null

    val clockDialog: MapClickInDialog by lazy {
        MapClickInDialog(requireActivity(), mAddr, object : SelectCallback() {
            override fun onResult(photos: ArrayList<Photo>?, isOriginal: Boolean) {

                LogUtil.d("mLatitude:$mLatitude,mLongitude:$mLongitude,mProjectId:$mProjectId")
                (activity as BaseMvpActivity<*, *>).goActivity(
                    ClockInComfirActivity::class.java,
                    arrayListOf(
                        Constant.CLOCK_IN_IMG,
                        Constant.LONGITUDE,
                        Constant.LATITUDE,
                        Constant.PROJECTID
                    ),
                    arrayListOf(photos?.get(0)?.path, "$mLongitude", "$mLatitude", mProjectId)
                )

            }

            override fun onCancel() {

            }

        })
    }

    private val myListener: BDAbstractLocationListener by lazy {

        object : BDAbstractLocationListener() {

            override fun onReceiveLocation(location: BDLocation) {
                //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
                //以下只列举部分获取经纬度相关（常用）的结果信息
                //更多结果信息获取说明，请参照类参考中BDLocation类中的说明
                val latitude = location.latitude //获取纬度信息
                val longitude = location.longitude //获取经度信息
                val radius = location.radius //获取定位精度，默认值为0.0f
                val coorType = location.coorType
                //获取经纬度坐标类型，以LocationClientOption中设置过的坐标类型为准
                val errorCode = location.locType
                //获取定位类型、定位错误返回码，具体信息可参照类参考中BDLocation类中的说明

                val addr = location.addrStr //获取详细地址信息

                val country = location.country //获取国家

                val province = location.province //获取省份

                val city = location.city //获取城市

                val district = location.district //获取区县

                val street = location.street //获取街道信息

                val adcode = location.adCode //获取adcode

                val town = location.town //获取乡镇信息

                if (location.poiList != null && !location.poiList.isEmpty()) {
                    val poi = location.poiList[0] as Poi
                    mPoiName = poi.name
                }
                LogUtil.d("mPoiName->$mPoiName")
                if (location.getPoiRegion() != null) {
                    val poiRegion = location.poiRegion
                    mPoiName = mPoiName + poiRegion.getDerectionDesc()
                }
                val Addr = "$city$district$street"
                LogUtil.d("mPoiName->$mPoiName")
                LogUtil.d("addr:$latitude,$longitude,$addr,$country,$province,$city,$district,$street,$adcode,${location.getLocationDescribe()}")
                tvAddr.setText("$Addr$mPoiName")
                mAddr = tvAddr.text.toString()
                mCity = city
                mprovince = province
                mArea = district


                mlocData = MyLocationData.Builder()
                    .accuracy(location.radius) // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(location.direction).latitude(location.latitude)
                    .longitude(location.longitude).build()
                LogUtil.d("locData->${GsonHelper.toJson(mlocData)},${null == bmapView},${null == bmapView.map}")
                bmapView.map.setMyLocationData(mlocData)
                mLatitude = latitude
                mLongitude = longitude
                if (isFirstLoc) {
//                    hideLoading()

                    if (mLatitude != 0.toDouble()) {
                        isFirstLoc = false
                    }
                    LogUtil.d("mLatitude:$mLatitude,mLongitude:$mLongitude")
                    val ll = LatLng(location.latitude, location.longitude)
//                    val bitmap = BitmapDescriptorFactory.fromResource(R.mipmap.home_move)
//
//                    val option: OverlayOptions = MarkerOptions()
//                        .position(ll)
//                        .icon(bitmap)
//                    bmapView.map.addOverlay(option)
//                    bitmap.recycle()
                    val builder = MapStatus.Builder()
                    builder.target(ll).zoom(18.0f)
                    bmapView.map.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()))

                    if (location.getLocType() == BDLocation.TypeServerError) {//服务器错误
                        ToastUtil.show("服务器错误，请检查")
                    } else if (location.getLocType() == BDLocation.TypeNetWorkException) {//网络错误器错误
                        ToastUtil.show("网络错误，请检查")
                    } else if (location.getLocType() == BDLocation.TypeCriteriaException) {//手机模式错误器错误
                        ToastUtil.show("手机模式错误，请检查是否飞行")
                    }
                }

            }
        }
    }

    fun requestLocation() {
        locationService.start()
        locationService.requestLocation()
        App.handler.postDelayed(
            {return2Local()},500
        )
    }

    fun return2Local() {
        if (mLatitude == 0.toDouble()) {

            locationStart()
        } else {
            val ll = LatLng(mLatitude, mLongitude)
            val builder = MapStatus.Builder()
            builder.target(ll).zoom(18.0f)
            bmapView.map.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()))
        }

    }

    private val scaleRatio = 5

    private val blurRadius = 10
    private var enterMenu: Dialog? = null

    companion object {
        fun newInstance(): MainFragment = MainFragment()
    }

    override fun createPresenter(): MainFragmentContract.Presenter = MainFragmentPresenter()

    override fun attachLayoutRes(): Int {
        return R.layout.fragment_main
    }


    override fun lazyLoad() {
//        showLoading()
        if (mProjectId.isNullOrEmpty()) {
            ToastUtil.show("请先选择项目")
            var intent = Intent(activity, ProjectUploadActivity::class.java)
            intent.putExtra("is_from_main", true)
            startActivity(intent)
        }
        tv_time.setText(DateUtils.formatToDay(FormatterEnum.HH_MM_SS))
        iv_current_position.setImageDrawable(
            R.mipmap.location.changeDrawalbeColor(
                requireActivity(),
                R.color.grey_ccc
            )
        )
        (activity as BaseMvpActivity<*, *>).countDown(object : OnCountDownCallBack {
            override fun countDowning(aLong: Long?) {
                val time = DateUtils.formatToDay(FormatterEnum.HH_MM_SS)
                if (null != tv_time) {
                    tv_time.post {
                        tv_time.setText(time)
                    }
                } else {
                    (activity as BaseMvpActivity<*, *>).disposeTimeCount()
                }
            }

            override fun countDownEnd() {

            }

        })



        SafeTipsDialog(activity as Context).show()


    }

    public fun locationStart() {
        App.singlePool.execute {
            while (null == bmapView) {

            }
            App.handler.post {
                locationService.initMapView(bmapView)
                locationService.registerListener(myListener)
                locationService.start()
                locationService.requestLocation()
            }
        }
    }


    override fun onResume() {
        bmapView.onResume()
        super.onResume()
        locationService.requestLocation()
    }

    override fun onPause() {
        bmapView.onPause()
        super.onPause()
    }

    override fun onDestroy() {
        if (null != bmapView) {
            bmapView.onDestroy()
        }
        super.onDestroy()
    }


    override fun initView(view: View) {
        super.initView(view)
        needShowLoading = false
        iv_menu.setOnClickListener { initMenuDialog() }

        rl_check.setOnClickListener {

            if (mProjectId.isNullOrEmpty()) {
                ToastUtil.show("请先选择项目")
                var intent = Intent(activity, ProjectUploadActivity::class.java)
                intent.putExtra("is_from_main", true)
                startActivity(intent)
                return@setOnClickListener
            }
            bmapView.map.snapshot {
                mBitmap?.recycle()
                clockDialog.setBitMap(WeakReference<Bitmap>(it)).show()
                mBitmap = it
            }
        }
        rlReturn.setOnClickListener {
            return2Local()
        }
//        tvAddr.setOnClickListener {
//        }
        tv_location.setOnClickListener {
            var intent = Intent(activity, ProjectUploadActivity::class.java)
            intent.putExtra("is_from_main", true)
            startActivity(intent)
        }

        tv_location.text = mProjiectName
        initProjectDisposable()
        mPresenter?.getWeatherIp()


    }


    private fun initMenuDialog() {

        val viewMenu: View = LayoutInflater.from(activity).inflate(
            R.layout.dialog_menu,
            null as ViewGroup?
        )
        when (UserInfoUtil.labour_type) {
            "1"->{
                viewMenu.findViewById<View>(R.id.rl_project_positioning).visibility = View.GONE
                viewMenu.findViewById<View>(R.id.rl_engineering_upload).visibility = View.GONE
            }
            "2"->{
                viewMenu.findViewById<View>(R.id.rl_project_positioning).visibility = View.GONE
            }
        }

        enterMenu = activity?.let { DialogUtil.showSelectDialog(it, viewMenu, 1) }
        enterMenu?.setCanceledOnTouchOutside(true)
        enterMenu?.show()
        viewMenu.findViewById<RelativeLayout>(R.id.rl_project_positioning).setOnClickListener {
            (activity as BaseMvpActivity<*, *>).goActivity(
                ClockInActivity::class.java,
                arrayListOf(Constant.ADDR, Constant.CITY, Constant.POINAME, Constant.LOCDATA,Constant.PROVINCE,Constant.DISTRICT),
                arrayListOf(mAddr, mCity, mPoiName, GsonHelper.toJson(mlocData),mprovince,mArea)
            )
        }
        viewMenu.findViewById<RelativeLayout>(R.id.rl_engineering_upload).setOnClickListener {
            val intent = Intent(activity, ProjectUploadActivity::class.java)
            startActivity(intent)
            enterMenu?.dismiss()
        }
        viewMenu.findViewById<RelativeLayout>(R.id.rl_msg).setOnClickListener {
            val intent = Intent(activity, MessageActivity::class.java)
            startActivity(intent)
            enterMenu?.dismiss()
        }
    }

    /**
     * 接收发送指令
     */
    @SuppressLint("AutoDispose")
    private fun initProjectDisposable() {
        mDisposable = RxBus.get().toFlowable(BusEvent.ProjectEvent::class.java)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                tv_location.text = it.projectName
                mProjectId = it.projectId
                mProjiectName = it.projectName
                project_addr = it.project_addr
            }
    }

    override fun showTips(tips: String) {

    }

    override fun setWeatherIpAdCode(adcode: String) {
        LogUtil.d("setWeatherIpAdCode:$adcode")
        mPresenter?.getWeather(adcode)
    }

    override fun setWeatherData(weatherBean: WeatherBean) {
        val data = weatherBean.forecasts
        val bean = WeatherForecastBean(
            weatherBean.now.text,
            "",
            weatherBean.now.temp,
            "",
            "",
            "",
            "",
            "",
            "",
            ""
        )
        //data.add(0, bean)
        rcyWeather.adapter = object : CustomRecyclerAdapter<WeatherForecastBean>(
            requireActivity(),
            R.layout.item_weather,
            data
        ) {
            override fun convert(holder: ViewHolder, t: WeatherForecastBean, position: Int) {
//                val date = if (position == 0) {
//                    "今日"
//                } else {
//                    t.week
//                }
                val date=t.week
                val res = when (t.text_day) {
                    "多云" -> {
                        R.mipmap.overcast
                    }
                    "小雨" -> {
                        R.mipmap.sun_rain
                    }
                    "大雨", "中雨" -> {
                        R.mipmap.rain
                    }
                    "晴" -> {
                        R.mipmap.sun
                    }
                    else -> {
                        R.mipmap.overcast
                    }
                }
                holder.setText(R.id.tvDay, date)
//                holder.setText(
//                    R.id.tvWeather,
//                    if (position == 0) "${t.text_day}${t.high}°c" else "${t.text_day}${t.low}~${t.high}°c"
//                )
                holder.setText(
                    R.id.tvWeather,
                     "${t.text_day}${t.low}~${t.high}°c"
                )
                holder.getView<ImageView>(R.id.ivWeather).setImageResource(res)

            }

        }
        rcyWeather.layoutManager =
            LinearLayoutManager(requireActivity(), RecyclerView.HORIZONTAL, false)
    }

    fun setErrorInfo(text: String, needShow: Boolean) {
        if (BuildConfig.DEBUG && needShow) {
            tvError.setText(text)
        }
    }


}